import api from "../config/api"
import { logout } from "./access"
import { getStorage, setStorage } from "./utils"
const report = require("./report.js")

/**
 * http请求
 * @param {string} options url 请求路径
 * @param {object} options data 请求数据
 * @param {string} options method 请求方式：OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
 * @param {object} options header 请求头
 * @param {boolean} options loading 是否显示请求loading，默认true
 * @param {boolean} options message 是否显示请求失败信息弹窗，默认true
 * @param {boolean} options token 是否添加token请求头，默认true
 * @param {*} options 其他参数
 */
function request(options) {
  const {
    url = '',
    header = {},
    loading = true,
    message = true,
    modal = true,
    token = true,
    timeout = 60000,
    ...otherProps
  } = options || {}

  // token
  const accessToken = getStorage("token")
  // 加载loading
  if (loading) {
    wx.showLoading({
      title: "加载中",
      mask: false,
    })
  }
  // 处理空值
  if (otherProps.data) {
    Object.keys(otherProps.data).forEach((key) => {
      if ([undefined, null].includes(otherProps.data[key])) {
        otherProps.data[key] = ''
      }
    })
  }
  return new Promise((resolve) => {
    wx.request({
      url: url.includes('/') ? url : api[url],
      header: {
        "content-type": "application/json",
        ...(token ? { token: accessToken } : {}),
        ...header
      },
      timeout: timeout,
      success: function (res) {
        const code = res?.data?.httpStatus || res?.statusCode
        report.reportParams({
          data: {
            url: url.includes('/') ? url : api[url],
            appName: "operational-tools",
            level: code == 200 ? "INFO" : "WARN",
            message: res?.data?.msg || "",
            param: JSON.stringify(otherProps.data||{}),
            token:accessToken,
            requestMethod: otherProps.method,
          },
        })

        if (res?.header?.Date) {
          setStorage('date', new Date(res?.header?.Date))
        }
        // 隐藏loading
        if (loading) {
          wx.hideLoading()
        }
       
        switch (code) {
          // 请求成功
          case 200:
            resolve(res.data)
            break;
          // 登录失效
          case 401:
            logout(modal)
            resolve(res)
            break;
          // 请求失败
          default:
            if (message) {
              if (res?.data?.msg?.includes('未登录')) {
                logout(modal)
              } else {
                wx.showToast({
                  title: res?.data?.msg || '请求失败',
                  icon: "none",
                })
              }
            }
            resolve(res.data)
            break;
        }
      },
      fail: function (err) {
        // 隐藏loading
        if (loading) {
          wx.hideLoading()
        }
        if (message) {
          if(timeout ===3000 || timeout ===5000){
            if(err.errMsg && err.errMsg.indexOf("请求超时") === -1){
              wx.showToast({
                title: err?.data?.msg || '请求失败',
                icon: "none",
              })
            }
          }else{
            wx.showToast({
              title: err?.data?.msg || '请求失败',
              icon: "none",
            })
          }
        }
        resolve(err)
      }, 
      ...otherProps,
    })
  })
}

/**
 * GET请求
 * @param {string} url 请求路径
 * @param {object} data 请求数据
 * @param {object} options 请求配置
 */
request.get = function (url, data, options) {
  return request({
    url,
    data,
    method: 'GET',
    ...options
  })
}

/**
 * POST请求
 * @param {string} url 请求路径
 * @param {object} data 请求数据
 * @param {object} options 请求配置
 */
request.post = function (url, data, options) {
  return request({
    url,
    data,
    method: 'POST',
    ...options
  })
}

/**
 * PUT请求
 * @param {string} url 请求路径
 * @param {object} data 请求数据
 * @param {object} options 请求配置
 */
request.put = function (url, data, options) {
  return request({
    url,
    data,
    method: 'PUT',
    ...options
  })
}

/**
 * DELETE请求
 * @param {string} url 请求路径
 * @param {object} data 请求数据
 * @param {object} options 请求配置
 */
request.delete = function (url, data, options) {
  return request({
    url,
    data,
    method: 'DELETE',
    ...options
  })
}

module.exports = request
